





let recorder = null;
let currentResult = null;


const recordBtn = document.getElementById('recordBtn');
const recordText = document.querySelector('.record-text');
const recordingStatus = document.getElementById('recordingStatus');
const uploadBtn = document.getElementById('uploadBtn');
const audioFileInput = document.getElementById('audioFileInput');
const uploadStatus = document.getElementById('uploadStatus');
const directionSelect = document.getElementById('direction');
const modeSelect = document.getElementById('mode');
const resultsDiv = document.getElementById('results');
const loadingDiv = document.getElementById('loading');
const loadingText = document.getElementById('loadingText');


const originalText = document.getElementById('originalText');
const translatedText = document.getElementById('translatedText');
const polishedText = document.getElementById('polishedText');
const audioPlayer = document.getElementById('audioPlayer');
const audioStatus = document.getElementById('audioStatus');
const addToVocabularyBtn = document.getElementById('addToVocabulary');
const xunfeiUsage = document.getElementById('xunfeiUsage');
const qwenUsage = document.getElementById('qwenUsage');


document.addEventListener('DOMContentLoaded', () => {
    console.log('🚀 页面加载完成');


    displayGreeting();


    recorder = new AudioRecorder();


    recordBtn.addEventListener('click', handleRecordButton);
    uploadBtn.addEventListener('click', handleUploadButton);
    audioFileInput.addEventListener('change', handleFileSelect);
    addToVocabularyBtn.addEventListener('click', handleAddToVocabulary);
});




function displayGreeting() {
    const now = new Date();
    const hour = now.getHours();
    let timeText = '';
    let greeting = '';

    if (hour >= 5 && hour < 12) {
        timeText = 'Bonjour! 早上好';
        greeting = '嗷呜（打哈欠），准备好开始一段新的冒险了吗，骚年 (ʃƪಡ ꇴ ಡ)<br>' +
                   '<em>Bonjour! Êtes-vous prêt pour une nouvelle aventure aujourd\'hui? 🌅</em>';
    } else if (hour >= 12 && hour < 14) {
        timeText = 'Bon appétit! 中午好';
        greeting = '今儿有点热啊，不过天气倒是不错哈，要不来瓶冰阔落 ᕦ(΄◞ิ ꇴ ◟ิ‵)<br>' +
                   '<em>Il fait chaud aujourd\'hui, mais le temps est magnifique! Que diriez-vous d\'une boisson fraîche? 🥤</em>';
    } else if (hour >= 14 && hour < 18) {
        timeText = 'Bon après-midi! 下午好';
        greeting = 'Bonjour，（呦），一眨眼竟然到下午了，要开始卷喽 (ㅍ△ㅍ๑)<br>' +
                   '<em>Bonjour! L\'après-midi est déjà là, c\'est l\'heure de se mettre au travail! 📚</em>';
    } else if (hour >= 18 && hour < 22) {
        timeText = 'Bonsoir! 晚上好';
        greeting = '月明星稀，乌鹊南飞，精彩的一天就要落幕喽，让我们一起回忆下精彩的一天吧 ( ͡° ͜ʖ ͡°)✧<br>' +
                   '<em>Bonsoir! La journée se termine, partageons ensemble les moments merveilleux d\'aujourd\'hui! 🌙</em>';
    } else {
        timeText = 'Bonne nuit! 深夜好';
        greeting = '还没睡还在卷呐，还是因为哪个小女生/小帅哥搁着网抑云呐，哎呀，不哭不哭，跟我聊聊呗，我的嘴就是肉包子打狗，有去无回 ٩(๛ ˘ ³˘)۶<br>' +
                   '<em>Encore éveillé? Travail ou chagrin d\'amour? Parlons-en ensemble, je suis là pour vous! 💙</em>';
    }

    const greetingTimeEl = document.getElementById('greetingTime');
    const greetingTextEl = document.getElementById('greetingText');

    if (greetingTimeEl && greetingTextEl) {
        greetingTimeEl.textContent = timeText;
        greetingTextEl.innerHTML = greeting;
    }
}




async function handleRecordButton() {
    if (!recorder.getStatus().isRecording) {

        const success = await recorder.start();
        if (success) {
            recordBtn.classList.add('recording');
            recordText.textContent = '停止录音';
            recordingStatus.textContent = '🔴 正在录音...';


            resultsDiv.style.display = 'none';
        }
    } else {

        try {
            recordBtn.disabled = true;
            recordText.textContent = '处理中...';
            recordingStatus.textContent = '⏳ 正在处理录音...';

            const audioBlob = await recorder.stop();


            recordBtn.classList.remove('recording');
            recordText.textContent = '开始录音';
            recordingStatus.textContent = '';
            recordBtn.disabled = false;


            await sendAudioToServer(audioBlob);

        } catch (error) {
            console.error('❌ 录音处理失败:', error);
            alert('录音处理失败: ' + error.message);

            recordBtn.classList.remove('recording');
            recordText.textContent = '开始录音';
            recordingStatus.textContent = '';
            recordBtn.disabled = false;
        }
    }
}




function handleUploadButton() {
    console.log('📁 点击上传按钮');

    audioFileInput.click();
}




async function handleFileSelect(event) {
    const file = event.target.files[0];

    if (!file) {
        console.log('❌ 未选择文件');
        return;
    }

    console.log('📁 选择文件:', file.name, '大小:', (file.size / 1024 / 1024).toFixed(2), 'MB');


    const validTypes = ['audio/mp3', 'audio/mpeg', 'audio/wav', 'audio/webm', 'audio/x-m4a', 'audio/mp4'];
    if (!validTypes.includes(file.type) && !file.name.match(/\.(mp3|wav|webm|m4a)$/i)) {
        alert('⚠️ 不支持的文件格式！\n请上传 MP3、WAV、WEBM 或 M4A 格式的音频文件。');
        audioFileInput.value = '';
        return;
    }


    const maxSize = 50 * 1024 * 1024;
    if (file.size > maxSize) {
        alert('⚠️ 文件太大！\n请上传小于 50MB 的音频文件。');
        audioFileInput.value = '';
        return;
    }


    uploadStatus.textContent = `📁 已选择: ${file.name}`;
    uploadStatus.style.color = '#4CAF50';


    resultsDiv.style.display = 'none';

    try {

        await sendFileToServer(file);


        audioFileInput.value = '';
        uploadStatus.textContent = '';
    } catch (error) {
        console.error('❌ 文件上传处理失败:', error);
        alert('文件上传处理失败: ' + error.message);
        audioFileInput.value = '';
        uploadStatus.textContent = '';
    }
}




async function sendFileToServer(file) {
    try {

        showLoading('正在上传音频文件...');


        const formData = new FormData();
        formData.append('audio', file);
        formData.append('direction', directionSelect.value);
        formData.append('mode', modeSelect.value);

        console.log('📤 发送文件到服务器...');
        console.log(`   文件名: ${file.name}`);
        console.log(`   方向: ${directionSelect.value}`);
        console.log(`   模式: ${modeSelect.value}`);


        showLoading('正在转录音频...');

        const response = await fetch('/api/translate', {
            method: 'POST',
            body: formData
        });

        hideLoading();

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error || '服务器错误');
        }

        const result = await response.json();

        if (result.success) {
            console.log('✅ 翻译成功');
            currentResult = result.data;
            displayResults(result.data);
        } else {
            throw new Error(result.error || '翻译失败');
        }

    } catch (error) {
        console.error('❌ 请求失败:', error);
        alert('翻译失败: ' + error.message);
        hideLoading();
    }
}




async function sendAudioToServer(audioBlob) {
    try {

        showLoading('正在上传音频...');


        const formData = new FormData();
        const audioFile = blobToFile(audioBlob, `recording_${Date.now()}.webm`);
        formData.append('audio', audioFile);
        formData.append('direction', directionSelect.value);
        formData.append('mode', modeSelect.value);

        console.log('📤 发送请求到服务器...');
        console.log(`   方向: ${directionSelect.value}`);
        console.log(`   模式: ${modeSelect.value}`);


        showLoading('正在转录音频...');

        const response = await fetch('/api/translate', {
            method: 'POST',
            body: formData
        });

        hideLoading();

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error || '服务器错误');
        }

        const result = await response.json();

        if (result.success) {
            console.log('✅ 翻译成功');
            currentResult = result.data;
            displayResults(result.data);
        } else {
            throw new Error(result.error || '翻译失败');
        }

    } catch (error) {
        console.error('❌ 请求失败:', error);
        alert('翻译失败: ' + error.message);
        hideLoading();
    }
}




function displayResults(data) {
    console.log('📊 显示结果:', data);


    resultsDiv.style.display = 'block';


    originalText.innerHTML = `<p>${escapeHtml(data.original_text)}</p>`;


    translatedText.innerHTML = `<p>${escapeHtml(data.translated_text)}</p>`;


    polishedText.innerHTML = `<p>${escapeHtml(data.polished_text)}</p>`;
    addToVocabularyBtn.style.display = 'inline-block';


    if (data.audio_path) {


        audioPlayer.src = data.audio_path;
        audioPlayer.style.display = 'block';
        audioStatus.style.display = 'none';
    } else {
        audioPlayer.style.display = 'none';
        audioStatus.textContent = '音频生成失败';
    }


    xunfeiUsage.textContent = `${data.usage.xunfei_chars} 字符`;
    qwenUsage.textContent = `${data.usage.qwen_tokens} tokens`;


    resultsDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}




async function handleAddToVocabulary() {
    if (!currentResult) {
        alert('没有可添加的内容');
        return;
    }

    try {
        const direction = directionSelect.value;
        const french = direction === 'fr2zh' ? currentResult.original_text : currentResult.polished_text;
        const chinese = direction === 'fr2zh' ? currentResult.polished_text : currentResult.original_text;

        const response = await fetch('/api/vocabulary', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                french: french,
                chinese: chinese,
                category: '翻译结果',
                generate_audio: true
            })
        });

        const result = await response.json();

        if (result.success) {
            alert('✅ 已添加到单词本！');
            addToVocabularyBtn.textContent = '✓ 已添加';
            addToVocabularyBtn.disabled = true;


            setTimeout(() => {
                addToVocabularyBtn.textContent = '➕ 添加到单词本';
                addToVocabularyBtn.disabled = false;
            }, 3000);
        } else {
            throw new Error(result.error || '添加失败');
        }

    } catch (error) {
        console.error('❌ 添加到单词本失败:', error);
        alert('添加失败: ' + error.message);
    }
}




function showLoading(text = '处理中...') {
    loadingText.textContent = text;
    loadingDiv.style.display = 'block';
    resultsDiv.style.display = 'none';
}




function hideLoading() {
    loadingDiv.style.display = 'none';
}




function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}




async function handleLogout() {
    if (!confirm('确定要登出吗？')) {
        return;
    }

    try {
        const response = await fetch('/api/auth/logout', {
            method: 'POST',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            window.location.href = '/login';
        } else {
            alert('登出失败：' + result.error);
        }
    } catch (error) {
        console.error('登出错误:', error);

        window.location.href = '/login';
    }
}


window.handleLogout = handleLogout;




window.addEventListener('beforeunload', () => {
    if (recorder) {
        recorder.release();
    }
});

